package com.nanbei.eduUcenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.nanbei.commonUntil.JwtUtils;
import com.nanbei.eduUcenter.entity.UcenterMember;
import com.nanbei.eduUcenter.service.UcenterMemberService;
import com.nanbei.eduUcenter.util.HttpClientUtils;
import com.nanbei.eduUcenter.util.WxLoginUtil;
import com.nanbei.servicebase.exceptionHandler.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@Controller
@RequestMapping("/api/ucenter/wx")
@CrossOrigin
public class WxLoginController {

    @Autowired
    private UcenterMemberService ucenterMemberService;

    /**
     * 生成微信扫描需要的二维码
     * @return
     */
    @GetMapping("/loginQRCode")
    public String loginQRCode(){
        String codeUrl="https://open.weixin.qq.com/connect/qrconnect"+
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        // 回调地址
        String redirectUrl = WxLoginUtil.WX_OPEN_REDIRECT_URL; //获取业务服务器重定向地址
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //url编码
        } catch (UnsupportedEncodingException e) {
            throw new GuliException(20001, e.getMessage());
        }

        //生成qrcodeUrl
        String qrcodeUrl = String.format(
                codeUrl,
                WxLoginUtil.WX_OPEN_APP_ID,
                redirectUrl,
                "nanbei");
        return "redirect:" + qrcodeUrl;
    }

    @GetMapping("/callback")
    public String  callback (String code ,String state){

        try {   //向认证服务器发送请求换取access_token
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
            "?appid=%s" +
            "&secret=%s" +
            "&code=%s" +
            "&grant_type=authorization_code";

            String accessTokenUrl = String.format(baseAccessTokenUrl,
                    WxLoginUtil.WX_OPEN_APP_ID,
                    WxLoginUtil.WX_OPEN_APP_SECRET,
                    code);



            // 请求这个拼接好的地址，得到两个返回值access_token 和 openid
            // 使用HttpClient发送请求得到结果
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);

            //重accessTokenInfo字符串中获取这两个值access_token 和 openid
            //吧accessTokenInfo字符串转化成map集合 根据map里面获取对应的值
            //使用json转换工具Gson
            Gson gson = new Gson();
            HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            String accessToken = (String) mapAccessToken.get("access_token");
            String openid = (String) mapAccessToken.get("openid");


            //根据openid判断数据库中是否包该用户
            QueryWrapper<UcenterMember> ucenterMemberQueryWrapper = new QueryWrapper<>();
             ucenterMemberQueryWrapper.eq("openid", openid);

            UcenterMember ucenterMember =null;
            ucenterMember = ucenterMemberService.getOne(ucenterMemberQueryWrapper);
            //如果没有这添加到数据库中
            if (ucenterMember==null){
                //访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);

                String userInfo = HttpClientUtils.get(userInfoUrl);
                // 将用户信息转换成字符串格式
                HashMap hashMap = gson.fromJson(userInfo, HashMap.class);
                String nickname = (String)hashMap.get("nickname");
                String headimgurl = (String)hashMap.get("headimgurl");

                //向数据库中插入一条记录
                ucenterMember = new UcenterMember();
                ucenterMember.setNickname(nickname);
                ucenterMember.setOpenid(openid);
                ucenterMember.setAvatar(headimgurl);
                ucenterMemberService.save(ucenterMember);
            }

            String token = JwtUtils.getJwtToken(ucenterMember.getId(),ucenterMember.getNickname());


            return "redirect:http://localhost:3000?token="+token;

        } catch (Exception e) {
            throw new GuliException(20001, "获取身份信息失败");
        }
    }
}
